<template>
  <div class="bill-detail-container">
    <div class="page-header">
      <el-button @click="goBack" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>账单详情</h1>
      <div class="header-actions" v-if="bill && bill.isMine">
        <el-button @click="handleEdit" circle size="large" class="edit-icon-btn">
          <el-icon><Edit /></el-icon>
        </el-button>
        <el-button @click="handleDelete" circle size="large" class="delete-icon-btn">
          <el-icon><Delete /></el-icon>
        </el-button>
      </div>
      <div v-else style="width: 40px;"></div>
    </div>

    <div v-loading="loading" class="detail-content">
      <div v-if="bill" class="bill-card">
        <!-- 金额 -->
        <div class="amount-section">
          <div class="amount-label">支出金额</div>
          <div class="amount-value">¥{{ formatAmount(bill.amount) }}</div>
        </div>

        <!-- 基本信息 -->
        <div class="info-section">
          <div class="info-item">
            <span class="label">📋 用途</span>
            <span class="value">{{ bill.purpose }}</span>
          </div>
          <div class="info-item">
            <span class="label">🏷️ 分类</span>
            <span class="value">{{ bill.category }}</span>
          </div>
          <div class="info-item">
            <span class="label">📅 日期</span>
            <span class="value">{{ formatDate(bill.billDate) }}</span>
          </div>
          <div class="info-item">
            <span class="label">👤 记账人</span>
            <span class="value">{{ bill.isMine ? '我' : '对方' }}</span>
          </div>
          <div class="info-item">
            <span class="label">📊 状态</span>
            <el-tag v-if="bill.status === 0" type="warning">待审批</el-tag>
            <el-tag v-else-if="bill.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="danger">已拒绝</el-tag>
          </div>
        </div>

        <!-- 拒绝理由 -->
        <div v-if="bill.status === 2 && bill.rejectReason" class="reject-section">
          <div class="reject-label">❌ 拒绝理由</div>
          <div class="reject-reason">{{ bill.rejectReason }}</div>
        </div>

        <!-- 截图 -->
        <div v-if="bill.images && bill.images.length > 0" class="images-section">
          <div class="images-label">📷 截图</div>
          <div class="images-grid">
            <el-image
              v-for="(img, index) in bill.images"
              :key="index"
              :src="getImageUrl(img)"
              :preview-src-list="bill.images.map(i => getImageUrl(i))"
              :initial-index="index"
              fit="cover"
              class="bill-image" />
          </div>
        </div>

        <!-- 审批按钮 -->
        <div v-if="bill.status === 0 && !bill.isMine" class="approval-actions">
          <el-button type="success" size="large" @click="approveBillAction(true)" round>
            ✅ 同意
          </el-button>
          <el-button type="danger" size="large" @click="showRejectDialog = true" round>
            ❌ 拒绝
          </el-button>
        </div>
      </div>
    </div>

    <!-- 拒绝理由对话框 -->
    <el-dialog v-model="showRejectDialog" title="拒绝理由" width="90%">
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef">
        <el-form-item label="拒绝理由" prop="rejectReason">
          <el-input
            v-model="rejectForm.rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请填写拒绝理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRejectDialog = false">取消</el-button>
        <el-button type="danger" @click="submitReject" :loading="submitting">确定拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Edit, Delete } from '@element-plus/icons-vue'
import { getBillDetail, approveBill, deleteBill } from '@/api'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const bill = ref(null)
const loading = ref(false)
const submitting = ref(false)
const showRejectDialog = ref(false)

const rejectForm = ref({ rejectReason: '' })
const rejectFormRef = ref(null)

const rejectRules = {
  rejectReason: [
    { required: true, message: '请填写拒绝理由', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
}

const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return import.meta.env.VITE_API_BASE_URL + url
}

const loadBillDetail = async () => {
  loading.value = true
  try {
    const res = await getBillDetail(route.params.id)
    if (res.code === 200) {
      const currentUserId = userStore.userInfo?.id
      bill.value = {
        ...res.data,
        isMine: res.data.userId === currentUserId,
        images: res.data.images ? JSON.parse(res.data.images) : []
      }
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '加载失败')
  } finally {
    loading.value = false
  }
}

const approveBillAction = async (approved) => {
  try {
    await ElMessageBox.confirm(`确定${approved ? '同意' : '拒绝'}此账单吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: approved ? 'success' : 'warning'
    })

    submitting.value = true
    const res = await approveBill({
      billId: bill.value.id,
      approved,
      rejectReason: null
    })

    if (res.code === 200) {
      ElMessage.success(approved ? '已同意' : '已拒绝')
      router.back()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const submitReject = async () => {
  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await approveBill({
          billId: bill.value.id,
          approved: false,
          rejectReason: rejectForm.value.rejectReason
        })

        if (res.code === 200) {
          ElMessage.success('已拒绝')
          showRejectDialog.value = false
          router.back()
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const goBack = () => {
  router.back()
}

// 编辑账单
const handleEdit = () => {
  router.push({
    path: '/bill/create',
    query: {
      id: bill.value.id,
      edit: true
    }
  })
}

// 删除账单
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除账单"${bill.value.purpose}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await deleteBill(bill.value.id)

    if (res.code === 200) {
      ElMessage.success('删除成功')
      router.back()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.msg || '删除失败')
    }
  }
}

onMounted(() => {
  loadBillDetail()
})
</script>

<style scoped>
.bill-detail-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.edit-icon-btn {
  background: linear-gradient(135deg, #ffa8b4 0%, #ff9a9e 100%);
  border: none;
  color: white;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.edit-icon-btn:hover {
  background: linear-gradient(135deg, #ffb8c4 0%, #ffaab0 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(255, 154, 158, 0.3);
}

.delete-icon-btn {
  background: linear-gradient(135deg, #ff7b8a 0%, #ff6b7a 100%);
  border: none;
  color: white;
  box-shadow: 0 2px 12px rgba(255, 107, 122, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.delete-icon-btn:hover {
  background: linear-gradient(135deg, #ff8b9a 0%, #ff7b8a 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(255, 107, 122, 0.3);
}

.bill-card {
  background: white;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
}

.amount-section {
  text-align: center;
  padding: 30px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.amount-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
}

.amount-value {
  font-size: 48px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.info-item .label {
  font-size: 14px;
  color: #666;
}

.info-item .value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.reject-section {
  background: #fff3e0;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
}

.reject-label {
  font-size: 14px;
  color: #ff9800;
  margin-bottom: 8px;
  font-weight: 500;
}

.reject-reason {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.images-section {
  margin-bottom: 24px;
}

.images-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.bill-image {
  width: 100%;
  height: 100px;
  border-radius: 8px;
  cursor: pointer;
}

.approval-actions {
  display: flex;
  gap: 12px;
}

.approval-actions .el-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

</style>

